<template>
  <div class="app-container">
    <!-- 搜索卡片 -->
    <el-card class="search-card" shadow="hover">
      <div slot="header" class="card-header">
        <span class="card-title">
          <i class="el-icon-search"></i>
          搜索条件
        </span>
        <div class="header-actions">
          <el-button type="text" @click="showSearch = !showSearch">
            {{ showSearch ? '收起' : '展开' }}
            <i :class="showSearch ? 'el-icon-arrow-up' : 'el-icon-arrow-down'"></i>
          </el-button>
          <el-button type="text" @click="resetQuery" icon="el-icon-refresh">重置</el-button>
        </div>
      </div>
      <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="80px">
        <el-row :gutter="20">
          <el-col :span="4">
            <el-form-item label="销售订单号" prop="salesOrderNumber">
              <el-input v-model="queryParams.salesOrderNumber" placeholder="请输入销售订单号" clearable @keyup.enter.native="handleQuery" />
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="物料名称" prop="materialName">
              <el-input v-model="queryParams.materialName" placeholder="请输入物料名称" clearable @keyup.enter.native="handleQuery" />
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="创建日期" prop="createDate">
              <el-date-picker clearable v-model="queryParams.createDate" type="date" value-format="yyyy-MM-dd" placeholder="请选择创建日期" />
            </el-form-item>
          </el-col>
          <el-col :span="4" style="display: flex; justify-content: flex-end; align-items: center;">
            <el-form-item>
              <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
              <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>

    <!-- 操作按钮卡片 -->
    <el-card class="action-card" shadow="hover">
      <div class="action-buttons">
        <div class="left-buttons">
          <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAdd" v-hasPermi="['bom:bom:add']">新增</el-button>
          <el-button type="success" icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate" v-hasPermi="['bom:bom:edit']">修改</el-button>
          <el-button type="danger" icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete" v-hasPermi="['bom:bom:remove']">删除</el-button>
          <el-button type="warning" icon="el-icon-download" size="mini" @click="handleExport" v-hasPermi="['bom:bom:export']">导出</el-button>
        </div>
        <div class="right-buttons">
          <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
        </div>
      </div>
    </el-card>

    <!-- 数据展示卡片 -->
    <el-card class="data-card" shadow="hover">
      <div slot="header" class="card-header">
        <span class="card-title">
          <i class="el-icon-s-operation"></i>
          BOM列表
        </span>
        <span class="card-subtitle">共 {{ total }} 条记录</span>
      </div>
      <el-table v-loading="loading" :data="bomList" @selection-change="handleSelectionChange" stripe border class="custom-table">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="销售订单号" align="center" prop="salesOrderNumber" />
        <el-table-column label="母件编码" align="center" prop="parentPartNumber" />
        <el-table-column label="物料名称" align="center" prop="materialName" />
        <el-table-column label=" 物料规格" align="center" prop="materialSpecification" />
        <el-table-column label="属性" align="center" prop="attribute" />
        <el-table-column label="序列号" align="center" prop="sn" />
        <el-table-column label="版本日期" align="center" prop="versionDate" width="180">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.versionDate, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="是否转工单" align="center" prop="isTransferWorkOrder">
          <template slot-scope="scope">
            <span>{{ scope.row.isTransferWorkOrder == 1 ? '是' : '否' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="备注" align="center" prop="remarks" />
      
        <el-table-column label=" 创建人" align="center" prop="creator" />
        <el-table-column label="创建日期" align="center" prop="createDate" width="180">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.createDate, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="最后修改人" align="center" prop="lastModifier" />
        <el-table-column label="最后修改日期" align="center" prop="lastModifyDate" width="180">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.lastModifyDate, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)" v-hasPermi="['bom:bom:edit']">修改</el-button>
            <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)" v-hasPermi="['bom:bom:remove']">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList" />
    </el-card>

    <!-- 添加或修改订单BOM对话框 -->
     <!-- 添加或修改订单BOM对话框 -->
     <el-dialog :title="title" :visible.sync="open" width="1200px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px" >
        <el-tabs v-model="activeTab" type="border-card">
          <el-tab-pane label="基本信息" name="basic">
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="母件编码" prop="parentPartNumber">
                  <el-input v-model="form.parentPartNumber" placeholder="请输入母件编码" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="物料名称" prop="materialName">
                  <div style="display: flex; align-items: center;">
                    <el-input v-model="form.materialName" placeholder="请输入物料名称" readonly style="flex: 1;" />
                    <el-button type="primary" icon="el-icon-folder" size="mini" @click="openMaterialSelector" style="margin-left: 10px; white-space: nowrap;">选择物料</el-button>
                  </div>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label=" 物料规格" prop="materialSpecification">
                  <el-input v-model="form.materialSpecification" placeholder="请输入 物料规格" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="属性" prop="attribute">
                  <el-input v-model="form.attribute" placeholder="请输入属性" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="序列号" prop="sn">
                  <el-input v-model="form.sn" placeholder="请输入序列号" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="版本日期" prop="versionDate">
                  <el-date-picker clearable v-model="form.versionDate" type="date" value-format="yyyy-MM-dd" placeholder="请选择版本日期" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="是否转工单" prop="isTransferWorkOrder">
                  <el-select v-model="form.isTransferWorkOrder" placeholder="请选择是否转工单">
                    <el-option label="是" :value="1" />
                    <el-option label="否" :value="0" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="备注" prop="remarks">
                  <el-input v-model="form.remarks" placeholder="请输入备注" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label=" 创建人" prop="creator">
                  <el-input v-model="form.creator" placeholder="请输入 创建人" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="创建日期" prop="createDate">
                  <el-date-picker clearable v-model="form.createDate" type="date" value-format="yyyy-MM-dd" placeholder="请选择创建日期" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="最后修改人" prop="lastModifier">
                  <el-input v-model="form.lastModifier" placeholder="请输入最后修改人" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="最后修改日期" prop="lastModifyDate">
                  <el-date-picker clearable v-model="form.lastModifyDate" type="date" value-format="yyyy-MM-dd" placeholder="请选择最后修改日期" />
                </el-form-item>
              </el-col>
            </el-row>

          </el-tab-pane>
          
          <!-- 新增子件BOM信息标签页 -->
          <el-tab-pane label="子件BOM信息" name="component" v-if="!form.salesOrderNumber">
            <div class="component-bom-container">
              <!-- 子件BOM操作按钮 -->
                             <div class="component-actions" style="margin-bottom: 20px;">
                 <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAddComponent">新增一行</el-button>
                
               </div>

              <!-- 子件BOM表格（行内编辑） -->
              <el-table
                v-loading="componentLoading"
                :data="componentBomList"
                stripe
                border
                class="component-table"
                height="300">
                <el-table-column type="index" label="序号" width="60" align="center" />
                <el-table-column label="子件名称" align="center" prop="componentName" width="160">
                  <template slot-scope="{ row }">
                    <el-input v-model="row.componentName" placeholder="子件名称" />
                  </template>
                </el-table-column>
                <el-table-column label="子件规格" align="center" prop="specification" width="140">
                  <template slot-scope="{ row }">
                    <el-input v-model="row.specification" placeholder="子件规格" />
                  </template>
                </el-table-column>
                <el-table-column label="物料分类" align="center" prop="category" width="120">
                  <template slot-scope="{ row }">
                    <el-input v-model="row.category" placeholder="物料分类" />
                  </template>
                </el-table-column>
                <el-table-column label="材料类型" align="center" prop="materialType" width="120">
                  <template slot-scope="{ row }">
                    <el-input v-model="row.materialType" placeholder="材料类型" />
                  </template>
                </el-table-column>
                <el-table-column label="表面处理" align="center" prop="surfaceTreatment" width="120">
                  <template slot-scope="{ row }">
                    <el-input v-model="row.surfaceTreatment" placeholder="表面处理" />
                  </template>
                </el-table-column>
                <el-table-column label="单位" align="center" prop="unit" width="90">
                  <template slot-scope="{ row }">
                    <el-input v-model="row.unit" placeholder="单位" />
                  </template>
                </el-table-column>
                <el-table-column label="属性" align="center" prop="attribute" width="120">
                  <template slot-scope="{ row }">
                    <el-input v-model="row.attribute" placeholder="属性" />
                  </template>
                </el-table-column>
                <el-table-column label="基本用量" align="center" prop="baseQuantity" width="110">
                  <template slot-scope="{ row }">
                    <el-input-number v-model="row.baseQuantity" :min="0" :precision="2" controls-position="right" style="width: 100%" />
                  </template>
                </el-table-column>
                <el-table-column label="子件损耗率(%)" align="center" prop="wastageRate" width="130">
                  <template slot-scope="{ row }">
                    <el-input-number v-model="row.wastageRate" :min="0" :max="100" :precision="2" controls-position="right" style="width: 100%" />
                  </template>
                </el-table-column>
                <el-table-column label="备注" align="center" prop="remarks" width="160">
                  <template slot-scope="{ row }">
                    <el-input v-model="row.remarks" placeholder="备注" />
                  </template>
                </el-table-column>
                <el-table-column label="操作" align="center" width="100" fixed="right">
                  <template slot-scope="{ row }">
                    <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDeleteComponent(row)">删除</el-button>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </el-tab-pane>
        </el-tabs>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 物料选择对话框 -->
    <el-dialog title="选择物料" :visible.sync="materialSelectorVisible" width="1200px" append-to-body>
      <!-- 搜索条件 -->
      <el-form :model="materialQueryParams" ref="materialQueryForm" size="small" :inline="true" label-width="80px" style="margin-bottom: 20px;">
        <el-form-item label="物料编码" prop="materialCode">
          <el-input v-model="materialQueryParams.materialCode" placeholder="请输入物料编码" clearable @keyup.enter.native="handleMaterialQuery" />
        </el-form-item>
        <el-form-item label="物料名称" prop="materialName">
          <el-input v-model="materialQueryParams.materialName" placeholder="请输入物料名称" clearable @keyup.enter.native="handleMaterialQuery" />
        </el-form-item>
        <el-form-item label="规格型号" prop="materialSpecification">
          <el-input v-model="materialQueryParams.materialSpecification" placeholder="请输入规格型号" clearable @keyup.enter.native="handleMaterialQuery" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleMaterialQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetMaterialQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 物料列表 -->
      <el-table v-loading="materialLoading" :data="materialList" @row-click="handleMaterialSelect" stripe border class="custom-table" height="400">
        <el-table-column label="物料编码" align="center" prop="materialCode" />
        <el-table-column label="物料名称" align="center" prop="materialName" />
        <el-table-column label="规格型号" align="center" prop="materialSpecification" />
        <el-table-column label="单位" align="center" prop="unit" />
        <el-table-column label="状态" align="center" prop="status">
          <template slot-scope="scope">
            <span>{{ scope.row.status == 1 ? '启用' : '停用' }}</span>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <pagination v-show="materialTotal > 0" :total="materialTotal" :page.sync="materialQueryParams.pageNum" :limit.sync="materialQueryParams.pageSize" @pagination="getMaterialList" />

      <div slot="footer" class="dialog-footer">
        <el-button @click="materialSelectorVisible = false">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 添加或修改子件BOM对话框 -->
   
    <el-dialog title="子件BOM信息" :visible.sync="componentDialogVisible" width="1000px" append-to-body>
      <el-form ref="componentForm" :model="componentForm" :rules="componentRules" label-width="100px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="子件名称" prop="componentName">
              <el-input v-model="componentForm.componentName" placeholder="请输入子件名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="子件规格" prop="specification">
              <el-input v-model="componentForm.specification" placeholder="请输入子件规格" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="物料分类" prop="category">
              <el-input v-model="componentForm.category" placeholder="请输入物料分类" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="材料类型" prop="materialType">
              <el-input v-model="componentForm.materialType" placeholder="请输入材料类型" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="表面处理" prop="surfaceTreatment">
              <el-input v-model="componentForm.surfaceTreatment" placeholder="请输入表面处理" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="单位" prop="unit">
              <el-input v-model="componentForm.unit" placeholder="请输入单位" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="属性" prop="attribute">
              <el-input v-model="componentForm.attribute" placeholder="请输入属性" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="基本用量" prop="baseQuantity">
              <el-input-number v-model="componentForm.baseQuantity" placeholder="请输入基本用量" :min="0" :precision="2" style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="子件损耗率" prop="wastageRate">
              <el-input-number v-model="componentForm.wastageRate" placeholder="请输入子件损耗率" :min="0" :max="100" :precision="2" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="备注" prop="remarks">
              <el-input v-model="componentForm.remarks" placeholder="请输入备注" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitComponentForm">确 定</el-button>
        <el-button @click="cancelComponent">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listBom, getBom, delBom, addBom, updateBom } from "@/api/bom/bom"
import { listMaterial } from "@/api/storage/material"
import { listErp_component_bom, addErp_component_bom, updateErp_component_bom, delErp_component_bom } from "@/api/bom/erp_component_bom"

export default {
  name: "Bom",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 订单BOM表格数据
      bomList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        salesOrderNumber: null,
        materialName: null,
        createDate: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        parentPartNumber: [
          { required: true, message: "母件编码不能为空", trigger: "blur" }
        ],
        materialName: [
          { required: true, message: "物料名称不能为空", trigger: "blur" }
        ],
        materialSpecification: [
          { required: true, message: "物料规格不能为空", trigger: "blur" }
        ],
        isTransferWorkOrder: [
          { required: true, message: "是否转工单不能为空", trigger: "blur" }
        ],
        creator: [
          { required: true, message: "创建人不能为空", trigger: "blur" }
        ],
        createDate: [
          { required: true, message: "创建日期不能为空", trigger: "blur" }
        ]
      },

      activeTab: 'basic', // 控制当前激活的tab
      
      // 子件BOM相关
      componentBomList: [],
      componentLoading: false,
      componentSelection: [],
      componentDialogVisible: false,
      componentForm: {},
      componentRules: {
        componentName: [
          { required: true, message: "子件名称不能为空", trigger: "blur" }
        ],
        specification: [
          { required: true, message: "子件规格不能为空", trigger: "blur" }
        ],
        category: [
          { required: true, message: "物料分类不能为空", trigger: "blur" }
        ],
        unit: [
          { required: true, message: "单位不能为空", trigger: "blur" }
        ],
        baseQuantity: [
          { required: true, message: "基本用量不能为空", trigger: "blur" }
        ],
        wastageRate: [
          { required: true, message: "子件损耗率不能为空", trigger: "blur" }
        ]
      },
      
      // 物料选择相关
      materialSelectorVisible: false,
      materialLoading: false,
      materialList: [],
      materialTotal: 0,
      materialQueryParams: {
        pageNum: 1,
        pageSize: 10,
        materialCode: null,
        materialName: null,
        materialSpecification: null,
      },
    }
  },
  created() {
    this.getList()
  },
  methods: {
    /** 查询订单BOM列表 */
    getList() {
      this.loading = true
      listBom(this.queryParams).then(response => {
        this.bomList = response.rows
        this.total = response.total
        this.loading = false
      })
    },

    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        salesOrderNumber: null,
        parentPartNumber: null,
        materialName: null,
        materialSpecification: null,
        attribute: null,
        sn: null,
        versionDate: null,
        isTransferWorkOrder: null,
        remarks: null,
        attachmentUploadStatus: null,
        creator: null,
        createDate: null,
        lastModifier: null,
        lastModifyDate: null
      }
      this.fileList = []
      this.resetForm("form")
      // 清空子件BOM
      this.componentBomList = []
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm")
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.salesOrderNumber)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    
    // 子件BOM相关
    /** 查询子件BOM列表（使用母件编码 parentPartNumber 作为后端 parentPartNumber） */
    getComponentBomList() {
      if (!this.form.parentPartNumber) return
      this.componentLoading = true
      const query = {
        parentPartNumber: this.form.parentPartNumber,
        pageNum: 1,
        pageSize: 100
      }
      listErp_component_bom(query).then(response => {
        this.componentBomList = response.rows || []
        this.componentLoading = false
      }).catch(() => {
        this.componentBomList = []
        this.componentLoading = false
      })
    },
    
    /** 新增子件一行 */
    handleAddComponent() {
      this.componentBomList.push({
        parentPartNumber: this.form.parentPartNumber || '',
        componentName: '',
        specification: '',
        category: '',
        materialType: '',
        surfaceTreatment: '',
        unit: '',
        attribute: '',
        baseQuantity: 0,
        wastageRate: 0,
        remarks: ''
      })
    },

    /** 保存行（新增/更新） */
    saveComponentRow(row) {
      const require = (v) => v !== undefined && v !== null && String(v).trim() !== ''
      if (!require(this.form.parentPartNumber)) {
        this.$message.error('请先选择母件（父物料）')
        return
      }
      if (!require(row.componentName) || !require(row.specification) || !require(row.unit)) {
        this.$message.error('请完善：子件名称、子件规格、单位')
        return
      }
      const payload = { ...row, parentPartNumber: this.form.parentPartNumber }
      if (row.componentId) {
        updateErp_component_bom(payload).then(() => {
          this.$modal.msgSuccess('保存成功')
          this.getComponentBomList()
        })
      } else {
        addErp_component_bom(payload).then(() => {
          this.$modal.msgSuccess('新增成功')
          this.getComponentBomList()
        })
      }
    },
    
    /** 编辑子件按钮操作 */
    handleEditComponent(row) {
      this.componentForm = { ...row }
      this.componentDialogVisible = true
    },
    
    /** 删除子件（支持批量） */
    handleDeleteComponent(row) {
      let componentIds = []
      let rowsToRemove = []
      
      if (row) {
        // 如果传入了具体的行，删除该行
        if (row.componentId) {
          componentIds = [row.componentId]
        } else {
          // 如果是新增的行（没有componentId），直接从列表中移除
          const index = this.componentBomList.findIndex(item => item === row)
          if (index !== -1) {
            this.componentBomList.splice(index, 1)
            this.$modal.msgSuccess("删除成功")
            return
          }
        }
      } else {
        // 批量删除选中的行
        const selectedRows = this.componentSelection
        for (const selectedRow of selectedRows) {
          if (selectedRow.componentId) {
            // 已保存的行，需要调用API删除
            componentIds.push(selectedRow.componentId)
          } else {
            // 新增的行，直接从列表中移除
            rowsToRemove.push(selectedRow)
          }
        }
        
        // 先移除新增的行
        for (const rowToRemove of rowsToRemove) {
          const index = this.componentBomList.findIndex(item => item === rowToRemove)
          if (index !== -1) {
            this.componentBomList.splice(index, 1)
          }
        }
        
        // 清空选择
        this.componentSelection = []
      }
      
      // 如果有需要调用API删除的数据
      if (componentIds.length > 0) {
        this.$modal.confirm('是否确认删除选中的子件BOM数据？').then(() => {
          return delErp_component_bom(componentIds)
        }).then(() => {
          this.getComponentBomList()
          this.$modal.msgSuccess("删除成功")
        }).catch(() => { })
      } else if (rowsToRemove.length > 0) {
        // 如果只是删除了新增的行，显示成功消息
        this.$modal.msgSuccess("删除成功")
      }
    },
    
    /** 校验并批量保存子件BOM行 */
    saveAllComponentRows() {
      // 若没有父物料，直接不处理子件
      if (!this.form.parentPartNumber) {
        return Promise.resolve()
      }
      const require = (v) => v !== undefined && v !== null && String(v).trim() !== ''
      // 过滤出有效行（至少填了名称或规格等任一字段）
      const rows = (this.componentBomList || []).map(r => ({
        ...r,
        parentPartNumber: this.form.parentPartNumber
      }))
      // 校验必填
      for (const row of rows) {
        // 如果整行都是空，则跳过
        const hasAny = Object.keys(row).some(k => require(row[k]))
        if (!hasAny) continue
        if (!require(row.componentName) || !require(row.specification) || !require(row.unit)) {
          this.$message.error('请完善子件BOM必填项：子件名称、子件规格、单位')
          return Promise.reject(new Error('component rows invalid'))
        }
      }
      // 逐行保存（新增或更新）
      const requests = rows
        .filter(row => require(row.componentName) || require(row.specification) || require(row.unit))
        .map(row => {
          if (row.componentId) {
            return updateErp_component_bom(row)
          }
          return addErp_component_bom(row)
        })
      if (requests.length === 0) return Promise.resolve()
      return Promise.all(requests).then(() => {
        this.getComponentBomList()
      })
    },
    
    /** 子件选择变化 */
    handleComponentSelectionChange(selection) {
      this.componentSelection = selection
    },
    
    /** 提交子件表单 */
    submitComponentForm() {
      this.$refs["componentForm"].validate(valid => {
        if (valid) {
          // 添加母件编码关联
          this.componentForm.parentPartNumber = this.form.parentPartNumber
          
          if (this.componentForm.componentId) {
            // 修改
            updateErp_component_bom(this.componentForm).then(response => {
              this.$modal.msgSuccess("修改成功")
              this.componentDialogVisible = false
              this.getComponentBomList()
            })
          } else {
            // 新增
            addErp_component_bom(this.componentForm).then(response => {
              this.$modal.msgSuccess("新增成功")
              this.componentDialogVisible = false
              this.getComponentBomList()
            })
          }
        }
      })
    },
    
    /** 取消子件操作 */
    cancelComponent() {
      this.componentDialogVisible = false
      this.resetComponentForm()
    },
    
    /** 重置子件表单 */
    resetComponentForm() {
      this.componentForm = {
        componentName: '',
        specification: '',
        category: '',
        materialType: '',
        surfaceTreatment: '',
        unit: '',
        attribute: '',
        baseQuantity: 0,
        wastageRate: 0,
        remarks: ''
      }
      this.resetForm("componentForm")
    },
    
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = "添加订单BOM"
      this.activeTab = 'basic'
    },
    
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const salesOrderNumber = row.salesOrderNumber || this.ids
      getBom(salesOrderNumber).then(response => {
        this.form = response.data
        this.open = true
        this.title = "修改订单BOM"
        this.activeTab = 'basic'
        // 载入子件BOM
        this.getComponentBomList()
      })
    },
    
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          const persistComponents = () => {
            return this.saveAllComponentRows()
              .then(() => {
                this.$modal.msgSuccess("保存成功")
                this.open = false
                this.getList()
              })
          }

          if (this.form.salesOrderNumber != null) {
            updateBom(this.form).then(() => {
              return persistComponents()
            })
          } else {
            addBom(this.form).then(() => {
              return persistComponents()
            })
          }
        }
      })
    },
    
    /** 删除按钮操作 */
    handleDelete(row) {
      const salesOrderNumbers = row.salesOrderNumber || this.ids
      this.$modal.confirm('是否确认删除订单BOM编号为"' + salesOrderNumbers + '"的数据项？').then(() => {
        return delBom(salesOrderNumbers)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => { })
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('bom/bom/export', {
        ...this.queryParams
      }, `bom_${new Date().getTime()}.xlsx`)
    },
    // 打开物料选择对话框
    openMaterialSelector() {
      this.materialSelectorVisible = true
      this.getMaterialList()
    },
    
    // 查询物料列表
    getMaterialList() {
      this.materialLoading = true
      listMaterial(this.materialQueryParams).then(response => {
        this.materialList = response.rows
        this.materialTotal = response.total
        this.materialLoading = false
      })
    },
    
    // 物料搜索
    handleMaterialQuery() {
      this.materialQueryParams.pageNum = 1
      this.getMaterialList()
    },
    
    // 重置物料搜索
    resetMaterialQuery() {
      this.resetForm("materialQueryForm")
      this.materialQueryParams.pageNum = 1
      this.getMaterialList()
    },
    
    // 选择物料
    handleMaterialSelect(row) {
      // 将选中的物料信息填充到表单中
      this.form.materialName = row.materialName
      this.form.materialSpecification = row.materialSpecification
      this.form.parentPartNumber = row.materialCode
      // 关闭物料选择对话框
      this.materialSelectorVisible = false
      this.$message.success('物料选择成功')
    }
  }
}
</script>

<style lang="scss" scoped>
.app-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 84px);
}

.search-card {
  margin-bottom: 20px;
  border-radius: 12px;
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 0;
    .card-title {
      font-size: 16px;
      font-weight: 600;
      color: #303133;
      i {
        margin-right: 8px;
        color: #409eff;
      }
    }
    .header-actions {
      display: flex;
      gap: 10px;
    }
  }
}

.action-card {
  margin-bottom: 20px;
  border-radius: 12px;
  .action-buttons {
    display: flex;
    justify-content: space-between;
    align-items: center;
    flex-wrap: wrap;
    gap: 10px;
    .left-buttons,
    .right-buttons {
      display: flex;
      gap: 10px;
      flex-wrap: wrap;
    }
  }
}

.data-card {
  border-radius: 12px;
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 0;
    .card-title {
      font-size: 16px;
      font-weight: 600;
      color: #303133;
      i {
        margin-right: 8px;
        color: #409eff;
      }
    }
    .card-subtitle {
      font-size: 14px;
      color: #909399;
    }
  }
}

.custom-table {
  border-radius: 8px;
  overflow: hidden;
  ::v-deep .el-table__header-wrapper {
    background-color: #fafafa;
  }
  ::v-deep .el-table__row {
    transition: all 0.3s ease;
    cursor: pointer;
    &:hover {
      background-color: #f5f7fa !important;
    }
  }
  ::v-deep .el-table__cell {
    padding: 12px 0;
  }
}

.component-bom-container {
  padding: 20px 0;
}

.component-actions {
  display: flex;
  gap: 10px;
  align-items: center;
}

.component-table {
  border-radius: 8px;
  overflow: hidden;
  
  ::v-deep .el-table__header-wrapper {
    background-color: #fafafa;
  }
  
  ::v-deep .el-table__row {
    transition: all 0.3s ease;
    cursor: pointer;
    
    &:hover {
      background-color: #f5f7fa !important;
    }
  }
  
  ::v-deep .el-table__cell {
    padding: 8px 0;
    font-size: 13px;
  }
}

::v-deep .el-card {
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  border: none;
  &:hover {
    box-shadow: 0 4px 20px 0 rgba(0, 0, 0, 0.15);
  }
}

::v-deep .el-button {
  border-radius: 8px;
  font-weight: 500;
  transition: all 0.3s ease;
  &.el-button--primary {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    border: none;
    &:hover {
      background: linear-gradient(135deg, #5a6fd8 0%, #6a4190 100%);
      transform: translateY(-2px);
    }
  }
  &.el-button--success {
    background: linear-gradient(135deg, #11998e 0%, #38ef7d 100%);
    border: none;
    &:hover {
      background: linear-gradient(135deg, #0f8a7d 0%, #2dd66e 100%);
      transform: translateY(-2px);
    }
  }
  &.el-button--danger {
    background: linear-gradient(135deg, #ff416c 0%, #ff4b2b 100%);
    border: none;
    &:hover {
      background: linear-gradient(135deg, #e63a5f 0%, #e64426 100%);
      transform: translateY(-2px);
    }
  }
  &.el-button--warning {
    background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
    border: none;
    &:hover {
      background: linear-gradient(135deg, #d884e2 0%, #d44e5f 100%);
      transform: translateY(-2px);
    }
  }
  &.el-button--info {
    background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
    border: none;
    &:hover {
      background: linear-gradient(135deg, #45a1f0 0%, #00e5f0 100%);
      transform: translateY(-2px);
    }
  }
}

::v-deep .el-pagination {
  margin-top: 20px;
  text-align: center;
}

::v-deep .el-dialog {
  border-radius: 12px;
  .el-dialog__header {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: white;
    border-radius: 12px 12px 0 0;
    .el-dialog__title {
      color: white;
      font-weight: 600;
    }
  }
}

::v-deep .el-form-item__label {
  font-weight: 500;
  color: #606266;
}

::v-deep .el-input__inner {
  border-radius: 8px;
  border: 1px solid #dcdfe6;
  transition: all 0.3s ease;
  &:focus {
    border-color: #409eff;
    box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
  }
}

::v-deep .el-select .el-input__inner {
  border-radius: 8px;
}

::v-deep .el-textarea__inner {
  border-radius: 8px;
  border: 1px solid #dcdfe6;
  transition: all 0.3s ease;
  &:focus {
    border-color: #409eff;
    box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
  }
}

::v-deep .el-tabs--border-card {
  border-radius: 8px;
  box-shadow: none;
  border: 1px solid #dcdfe6;
}
::v-deep .el-tabs--border-card>.el-tabs__header {
  background-color: #f5f7fa;
  border-bottom: 1px solid #dcdfe6;
}
::v-deep .el-tabs--border-card>.el-tabs__header .el-tabs__item {
  border-radius: 6px 6px 0 0;
  margin-right: 5px;
  &.is-active {
    background-color: #409eff;
    color: white;
    border-color: #409eff;
  }
}
</style>
